import React, { Component } from 'react';
import styles from './index.less';

// 远程加载js （按需引入）
export function loadFabric() {
  return new Promise(function(resolve, reject) {
    if (window.luckysheet) {
      resolve();
      return;
    }

    var urls = [
      // js
      'https://cdn.jsdelivr.net/npm/fabric@4.1.0',
    ];

    loadjs(urls, {
      async: false,
      success: function() {
        resolve();
      },
    });
  });
}

export default class extends Component {
  componentDidMount = async () => {
    await loadFabric();
    // 创建画布
    const canvas = new fabric.Canvas('canvas-container', {
      width: 800,
      height: 600,
      backgroundColor: '#fff',
    });

    // 创建方块
    const square = new fabric.Rect({
      left: 100,
      top: 100,
      width: 400,
      height: 400,
      fill: 'red',
    });
    canvas.add(square);

    // 创建要添加的元素
    const circle = new fabric.Circle({
      left: 50,
      top: 50,
      radius: 50,
      fill: 'blue',
    });

    const text = new fabric.Text('Hello', {
      left: 150,
      top: 150,
      fontSize: 24,
      fill: 'white',
    });

    // 创建一个组合元素，并将元素添加到组合中
    const group = new fabric.Group([circle, text], {
      left: square.left,
      top: square.top,
    });

    // 将组合元素添加到方块中
    square.set('objects', [group]);
    canvas.renderAll();

    // 启用滚轮缩放
    canvas.on('mouse:wheel', function(event) {
      const delta = event.e.deltaY;
      let zoom = canvas.getZoom();
      zoom *= 0.999 ** delta;

      // 设置缩放边界
      if (zoom > 10) zoom = 10;
      if (zoom < 0.01) zoom = 0.01;

      canvas.zoomToPoint({ x: event.e.offsetX, y: event.e.offsetY }, zoom);
      event.e.preventDefault();
      event.e.stopPropagation();
    });

    // 启用左右移动
    canvas.on('mouse:move', function(event) {
      if (event && event.e && event.e.buttons === 1) {
        const delta = new fabric.Point(event.e.movementX, event.e.movementY);
        canvas.relativePan(delta);
      }
    });
  };
  render() {
    return (
      <div className={styles.container}>
        <canvas id="canvas-container" className={styles.canvas}></canvas>
      </div>
    );
  }
}
